package com.hub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hub.dto.LoginStateBean;
import com.hub.dto.PageParam;
import com.hub.dto.auth.CreateUserParam;
import com.hub.dto.auth.UserRoleParam;
import com.hub.entity.AuthRole;
import com.hub.entity.AuthUserInfo;
import com.hub.entity.AuthUserRole;
import com.hub.frame.consts.ConstantUtil;
import com.hub.frame.pojo.CachedUserInfo;
import com.hub.frame.pojo.Security;
import com.hub.frame.service.cache.ICached;
import com.hub.frame.service.security.IAuthService;
import com.hub.utils.ApiResultObject;
import com.hub.mapper.AuthRoleMapper;
import com.hub.mapper.AuthUserInfoMapper;
import com.hub.mapper.AuthUserRoleMapper;
import com.hub.service.IAuthUserInfoService;
import com.hub.service.IAuthUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hub
 * @since 2020-05-13
 */
@Service
public class AuthUserInfoServiceImpl extends BaseServiceImpl<AuthUserInfoMapper, AuthUserInfo> implements IAuthUserInfoService {

    @Autowired
    private IAuthService authService;
    @Resource
    private AuthUserInfoMapper authUserInfoMapper;
    @Resource
    private AuthUserRoleMapper authUserRoleMapper;
    @Resource
    private AuthRoleMapper authRoleMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ICached cached;
    @Autowired
    private IAuthUserRoleService authUserRoleService;

    @Override
    public ApiResultObject getList(PageParam<AuthUserInfo> pageParam) {
        Page<AuthUserInfo> page = pageParam.getPage();
        AuthUserInfo param = pageParam.getParams();
        QueryWrapper<AuthUserInfo> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getUserName())){
            wrapper.like("user_name", param.getUserName());
        }
        if(StringUtils.isNotEmpty(param.getAccount())){
            wrapper.like("account", param.getAccount());
        }
        wrapper.eq("active_flg", ConstantUtil.YES);
        return ApiResultObject.success(authUserInfoMapper.selectPage(page, wrapper));
    }

    @Override
    public ApiResultObject getUserDetail(Long id) {
        return ApiResultObject.success(authUserInfoMapper.selectById(id));
    }

    @Override
    public ApiResultObject getUserRole(UserRoleParam param) {
        QueryWrapper<AuthUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", param.getUserId());
        List<AuthUserRole> list = authUserRoleMapper.selectList(wrapper);
        List<Long> result = list.stream().map(item -> {
            return item.getRoleId();
        }).collect(Collectors.toList());
        return ApiResultObject.success(result);
    }

    @Override
    public ApiResultObject updateUser(Long id, CreateUserParam param) {
        AuthUserInfo authUserInfo = authUserInfoMapper.selectById(id);
        authUserInfo.setUserName(param.getUserName());
        authUserInfo.setRemark(param.getRemark());
        authUserInfo.setPassword(param.getPassword());
        authUserInfo.setActiveFlg(ConstantUtil.YES);
        authUserInfoMapper.updateById(authUserInfo);
        return ApiResultObject.success();
    }

    @Override
    public ApiResultObject updateUserRole(UserRoleParam param) {
        QueryWrapper<AuthUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", param.getUserId());
        authUserRoleMapper.delete(wrapper);

        List<Long> roleIds = param.getRoleIds();
        if(roleIds != null && roleIds.size() > 0){
            List<AuthUserRole> list = roleIds.stream().map(roleId -> {
                AuthUserRole authUserRole = new AuthUserRole();
                authUserRole.setUserId(param.getUserId());
                authUserRole.setRoleId(roleId);
                return authUserRole;
            }).collect(Collectors.toList());
            authUserRoleService.saveBatch(list);
        }
        return ApiResultObject.success();
    }

    @Override
    public ApiResultObject createUser(CreateUserParam param) {
        //检验账号是否存在
        String account = param.getAccount();
        QueryWrapper<AuthUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        wrapper.eq("active_flg", ConstantUtil.YES);
        if(this.count(wrapper) > 0){
            return ApiResultObject.failed("账号已存在，请重新输入！");
        }

        //插入数据库
        AuthUserInfo authUserInfo = new AuthUserInfo();
        authUserInfo.setAccount(account);
        authUserInfo.setUserName(param.getUserName());
        authUserInfo.setPassword(param.getPassword());
        authUserInfo.setRemark(param.getRemark());
        if(this.save(authUserInfo)){
            return ApiResultObject.success();
        }
        return ApiResultObject.failed();
    }

    @Override
    public ApiResultObject delete(Long id) {
        if(this.removeById(id)){
            return ApiResultObject.success();
        }
        return ApiResultObject.failed();
    }

    @Override
    public ApiResultObject login(String account, String password) throws Exception {
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(password)){
            return ApiResultObject.failed("用户名或密码错误！");
        }
        //根据用户名查询用户信息
        AuthUserInfo authUserInfo = authUserInfoMapper.selectUserInfoByAccount(account);
        if(ObjectUtils.isEmpty(authUserInfo)){
            return ApiResultObject.failed("用户名或密码错误！");
        }
        String realPwd = authUserInfo.getPassword();
        if (StringUtils.isNotEmpty(realPwd)) {
//            if (!realPwd.equalsIgnoreCase(MD5Util.MD5(password))) {
//                return ApiResultObject.failed("用户名或密码错误！");
//            }
            if(!realPwd.equals(password)){
                return ApiResultObject.failed("用户名或密码错误！");
            }
        }
        //查询用户角色信息
        List<AuthRole> roleList = authRoleMapper.selectByUserId(authUserInfo.getId());
        AuthRole authRole = new AuthRole();
        if(roleList != null && roleList.size() > 0){
            authRole = roleList.get(0);
        }
        //添加缓存
        return ApiResultObject.success(this.generateLoginState(authUserInfo, authRole));
    }

    @Override
    public AuthUserInfo findUserInfoByAccount(String username) {
        return authUserInfoMapper.selectUserInfoByAccount(username);
    }

    @Override
    public ApiResultObject loadMenuInfo() {
        String token = request.getHeader(ConstantUtil.X_ACCESS_TOKEN);
        Object obj = cached.getObj(token);
        if(obj == null){
            return ApiResultObject.failed("获取用户信息失败");
        }
        CachedUserInfo cachedObj = (CachedUserInfo) obj;
        String userId = cachedObj.getUserId();
        if(StringUtils.isEmpty(userId)){
            return ApiResultObject.failed("获取用户信息失败");
        }
        return ApiResultObject.success(authUserInfoMapper.selectMenuByUserId(userId));
    }

    @Override
    public ApiResultObject logout() {
        String token = request.getHeader(ConstantUtil.X_ACCESS_TOKEN);
        authService.removeAuthInfo(token);
        return ApiResultObject.success();
    }

    /**
     * 添加缓存
     * @param authUserInfo
     * @param authRole
     * @return
     * @throws Exception
     */
    LoginStateBean generateLoginState(AuthUserInfo authUserInfo, AuthRole authRole) throws Exception {
        LoginStateBean loginState = new LoginStateBean();
        Long userId = authUserInfo.getId();
        Long roleId = authRole.getId();
        Security security = authService.setAuthInfo(String.valueOf(userId), String.valueOf(roleId), authUserInfo.getUserName());
        //自定义的登录态
        loginState.setSecurity(security);
        loginState.setAuthUserInfo(authUserInfo);
        return loginState;
    }
}
